package tests.read;

import static org.junit.Assert.*;


import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;
import model.Subline;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.SublineInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

/*
 * 
 * Attempts to fetch the a line with number 3 in a budget with lines 1 and 2
 * should return false positive
 * 
 */

public class SublineQueryTest02
{
	Budget budget;
	BudgetFactory factory;
	Line line;
	Subline s1;
	Subline s2;

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        
        line = (Line) budget.createLine();
		budget.add(line);
		
		s1 = (Subline) line.createSubline();
		s1.setNumber(1);
		s2 = (Subline) line.createSubline();
		s2.setNumber(2);
		line.add( (SublineInterface)s1);
		line.add( (SublineInterface) s2);
		
		budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete(s1, "Sublines", WorkletContext.getInstance());
		Helper.delete(s2, "Sublines", WorkletContext.getInstance());
		Helper.delete(line, "Lines", WorkletContext.getInstance());
		Helper.delete(budget, "Budgets", WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		try
		{
			BasicDBObject or = new BasicDBObject("entry.number", 3);
			String criteria = JSON.serialize(or);
			
			@SuppressWarnings("unchecked")
			ArrayList<SublineInterface> sublines  =  Helper.query("Sublines", criteria, WorkletContext.getInstance());
		
			for(SublineInterface subline : sublines)
			{
				Integer number = ((Subline) subline).getNumber();
					
				if(number != 1 || number != 2)
				{
					fail("Subline number query passed when it should have failed");
				}
			}
		}
		catch(Exception e)
		{
			fail("Subline incorrect number query failed with exception " + e);
		}
	}
}